package org.ysh.service;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;
import org.ysh.domain.Archive;
import org.ysh.mapper.ArchiveMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SolrService {

    @Resource
    private ArchiveMapper archiveMapper;

    /**
     * 提交案卷数据到Solr
     * @param archiveList
     */
    public void commitArchiveToSolr(List<Archive> archiveList) throws Exception{
        if(CollectionUtils.isNotEmpty(archiveList)){
            List<SolrInputDocument> documents = archiveList.stream().parallel().map(archive -> {
                SolrInputDocument document = new SolrInputDocument();
                document.addField("id", archive.getId() + "");
                document.addField("archiveNo", archive.getArchiveNo());
//                document.addField("unitPlace", archive.getUnitPlace());
                document.addField("fondsCode", archive.getFondsCode());
                document.addField("classificationCode", archive.getClassificationCode());
                document.addField("year", archive.getYear());
//                document.addField("catalogName", archive.getCatalogNo());
                document.addField("duration", archive.getDuration());
                document.addField("fileNo", archive.getFileNo());
                document.addField("title", archive.getTitle());
//                document.addField("startYearMonth", archive.getStartYearMonth() == null ? "" : DateFormatUtils.format(archive.getStartYearMonth(), "yyyy-MM-dd"));
//                document.addField("endYearMonth", archive.getEndYearMonth() == null ? "" : DateFormatUtils.format(archive.getEndYearMonth(), "yyyy-MM-dd"));
//                document.addField("fileCount", archive.getFileCount());
                document.addField("pageCount", archive.getPageCount());
                return document;
            }).collect(Collectors.toList());

            String url = "http://localhost:8983/solr/jiyang_archive";
            try(HttpSolrClient solr = new HttpSolrClient.Builder(url).build()){
                UpdateRequest req = new UpdateRequest();
                req.setAction(UpdateRequest.ACTION.COMMIT, false, false);
                req.add(documents);
                req.process(solr);
            }
        }
    }


}
